<template>
  <AxiomPlaygroundLayout :initial-sidebar-width="400">
    <template #default>
      <ChatPanel :messages="messages" :loading="isLoading" @send-message="handleSendMessage" />
    </template>
    
    <template #sidebar-content>
      <SettingsPanel ref="settingsPanelRef" />
    </template>
  </AxiomPlaygroundLayout>
</template>

<script setup>
import { ref, inject } from 'vue';
import { AxiomPlaygroundLayout } from 'axiom-view';
import { chatApi } from '@/api/ai/chat';
import ChatPanel from './components/ChatPanel.vue';
import SettingsPanel from './components/SettingsPanel.vue';

defineOptions({
  name: 'AIChatView',
});

const settingsPanelRef = ref(null);
const messages = ref([]);
const isLoading = ref(false);
const { notification } = inject('axiom-utils');

let messageIdCounter = 0;
let abortController = null;

async function handleSendMessage({ query, system_prompt }) {
  if (isLoading.value) {
    if (abortController) {
      abortController.abort();
      notification.info({ title: '操作取消', message: '已中断上一次的流式请求' });
    }
    return;
  }
  if (!settingsPanelRef.value) return;

  const settings = settingsPanelRef.value.getSettings();
  if (!settings.kb_ids || settings.kb_ids.length === 0) {
    notification.warning({ title: '提示', message: '请至少选择一个知识库进行查询。' });
    return;
  }
  if (!settings.search_config) {
    notification.warning({ title: '提示', message: '请选择一个知识库查询预设。' });
    return;
  }
   if (!settings.llm_profile_name) {
    notification.warning({ title: '提示', message: '请选择一个语言模型。' });
    return;
  }

  messages.value.push({
    id: messageIdCounter++,
    role: 'user',
    content: query,
  });

  const assistantMessageId = messageIdCounter++;
  messages.value.push({
    id: assistantMessageId,
    role: 'assistant',
    content: '',
  });
  
  isLoading.value = true;
  abortController = new AbortController();

  try {
    const payload = {
      search: {
        ...settings.search_config,
        query: query,
        kb_ids: settings.kb_ids,
      },
      llm_profile_name: settings.llm_profile_name,
      system_prompt: system_prompt,
    };

    await chatApi.queryStream(
      payload,
      (delta) => {
        const assistantMessage = messages.value.find(m => m.id === assistantMessageId);
        if (assistantMessage) {
          assistantMessage.content += delta;
        }
      },
      abortController.signal
    );

  } catch (error) {
    if (error.name !== 'AbortError') {
      const assistantMessage = messages.value.find(m => m.id === assistantMessageId);
      if (assistantMessage) {
         assistantMessage.content = `发生错误: ${error.message}`;
      }
    }
  } finally {
    isLoading.value = false;
    abortController = null;
  }
}
</script>